import router from '@/router';
import axios from 'axios'
import { ElMessage } from 'element-plus';

//创建axios实例对象
const request = axios.create({
  baseURL: '/api',
  timeout: 600000
})

//axios的请求 request 拦截器
request.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if(token){
    config.headers.token = token
  }
  return config;
},  (error) => {
  return Promise.reject(error);
});

//axios的响应 response 拦截器
request.interceptors.response.use(
  (response) => { //成功回调
    return response.data
  },
  (error) => { //失败回调
    if(error.status == 401){ //token 失效
      ElMessage.error('登录已失效，请重新登录')
      router.push('/login')
    }else {
      ElMessage.error('网络异常，请稍后再试')
    }
    return Promise.reject(error)
  }
)

export default request